package com.csy.commons.core.controller;

import java.util.List;

import com.csy.commons.constant.HttpStatus;
import com.csy.commons.core.domain.BaseResponse;
import com.csy.commons.core.page.PageDomain;
import com.csy.commons.core.page.PageResult;
import com.csy.commons.core.utils.ServletUtils;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;

/**
 * 基础控制类
 * @Auther: sunxx
 * @Date: 2023/12/31 - 12 - 31 - 20:01
 * @Description: com.sxx.ajcommunity.common.core.controller
 * @version: 1.0
 */
public class BaseController {

    /* 当前记录起始索引 */
    public static final String PAGE_NUM = "pageNum";

    /* 每页显示记录数 */
    public static final String PAGE_SIZE = "pageSize";

    /*
    * 分装分页数据
    *  */
    public static PageDomain getPageDomain(){

        PageDomain pageDomain = new PageDomain();
        Integer pageNum = ServletUtils.getParameterToInt(PAGE_NUM);
        if (pageNum.intValue() > 0) {
        	pageDomain.setPageNum(pageNum);
        }
        
        Integer pageSize = ServletUtils.getParameterToInt(PAGE_SIZE);
        if (pageSize.intValue() > 0) {
        	pageDomain.setPageSize(pageSize);
        }

        return pageDomain;
    }

    /*
    * 封装调用PageHelper的startPage方法
    * */
    protected void startPage(){
        PageDomain pageDomain = getPageDomain();
        Integer pageNum = pageDomain.getPageNum();
        Integer pageSize = pageDomain.getPageSize();

        if (pageNum != null && pageSize != null){
            PageHelper.startPage(pageNum,pageSize);
        }

    }

    /*
    * 响应分页数据
    * */
    protected <T> PageResult getData(List<T> list){
        PageResult pageResult = new PageResult();
        pageResult.setCode(HttpStatus.SUCCESS);
        pageResult.setMsg("分页查询成功");
        pageResult.setRows(list);
        pageResult.setTotal(new PageInfo<T>(list).getTotal());
        return pageResult;
    }

    /*
    * 响应返回结果（针对增删改 操作）
    * */
    protected BaseResponse<Integer> toAjax(int rows){
        return rows > 0 ? BaseResponse.success(rows) : BaseResponse.fail("操作失败");
    }



}
